import echarts from '../../../ec-canvas/echarts'
import geoJson from '../../../ec-canvas/china.js'
const app = getApp()
const {
  ActivityModel
} =  require('../../../../utils/activity-model.js')
var activityModel = new ActivityModel();
const {
  MemberModel
} = require('../../../../utils/member-model.js');
var memberModel = new MemberModel();
function initChart(canvas, width, height) {
  const getPixelRatio = () => {
    let pixelRatio = 0
    wx.getSystemInfo({
      success: function (res) {
        pixelRatio = res.pixelRatio
      },
      fail: function () {
        pixelRatio = 0
      }
    })
    return pixelRatio
  }
  var dpr = getPixelRatio()
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr
  });
  canvas.setChart(chart);

  //  去掉地图上未参加活动的省份name
  let proList = provinceData.map(item => item.provinceName.replace(/省|市/g,''))
  geoJson.features.forEach(item => {
    if (!proList.includes(item.properties.name)){
      item.properties.name = ' '
    }
  })
  
  echarts.registerMap('china', geoJson)
  // 初始参加活动的省份数据
 let allpro = []
 let lightNum = 0
  provinceData.forEach(item => {
    if (userMedalData.map(item => item.provinceId).includes(item.provinceId)) {
      if (item.shopList.length === userMedalData.filter(useritem => useritem.provinceId === item.provinceId)[0].shopList.length) {
        allpro.push({
          name: item.provinceName.replace(/省|市/g,''),
          value: 3
        })
        lightNum++
      }else{
        allpro.push({
          name: item.provinceName.replace(/省|市/g,''),
          value: 2
        })
      }
    }else{
      allpro.push({
        name: item.provinceName.replace(/省|市/g,''),
        value: 1
      })
    }
  })
  _this.setData({
    lightNum:lightNum
  })
  // 去掉地图点击变色
 chart.on("mouseover", function (params){
  if (params.componentType === 'series') {
    chart.dispatchAction({
      type: 'downplay'
    });
  }
});

// 绑定省份点击事件
  chart.on('click', function (params) {
    if (params.componentType === 'series') {
      if (params.name) {
        // for(var i=0;i<allpro.length;i++){ // 点击高亮
        //   allpro[i].value=1;
        //   if(params.name == allpro[i].name){
        //     allpro[i].value=2;
        //   }
        // }
        // chart.setOption(option);
        wx.navigateTo({
          url: '/activityModule/activity/collectCards/medal/areaRank/index?provinceId=' + provinceData.filter(item => item.provinceName.indexOf(params.name)!=-1)[0].provinceId,
        })
      }
    }
  })

  var convertData = function(data) {
    var res = [];
    for (var i = 0; i < data.length; i++) {
      geoJson.features.forEach(item => {
        if (item.properties.name == data[i].name) {
          var geoCoord = item.properties.cp
          if (geoCoord) {
              res.push({
                  name: data[i].name,
                  value: geoCoord.concat(data[i].value)
              });
          }
        }
      })
    }
    return res;
};


  var option = {
    geo: [
      {
        // 地理坐标系组件
        map: "china",
        roam: true, // 可以缩放和平移
        // symbol: 'http://oss-test.kiscloud.net/image/other/other/20201104/20201104123425_618.png',
        aspectScale: 0.8, // 比例
        scaleLimit: {
          min: 1,
          max: 25
        },
        layoutCenter: ["50%", "50%"], // position位置
        layoutSize: 370, // 地图大小，保证了不超过 370x370 的区域
        label: {
          // 图形上的文本标签
          normal: {
            show: true,
            textStyle: {
              color: "#333",
              fontSize: '8'
            }
          }
        },
        itemStyle: {
          // 图形上的地图区域
          normal: {
            borderColor: "#666",
            borderType: "dashed",
            areaColor: "#fff"
          }
        }
      }
    ],
    series: [
      {
        type: 'map',
        mapType: 'china',
        // zoom: 2,
        geoIndex: 0,
        roam: false, // 鼠标是否可以缩放
        label: {
          normal: {
            show: false
          },
          emphasis: {
            show: false
          }
        },
        data: allpro
      }
    //   {
               
    //     type: 'scatter',
    //     roam : false,
    //     symbol: 'http://oss-test.kiscloud.net/image/other/other/20201104/20201104123425_618.png',
    //     symbolSize: 30,
    //     coordinateSystem: 'geo',
    //     data: convertData(allpro.filter(item => item.value == 3)),
    //     label: {
    //         emphasis: {
    //             show: false
    //         }
    //     }
    // }
    ],
    dataRange: {
      x: '-1000px',
      y: '-1000px',
      splitList: [
        { start: 1, end: 1, color: '#ffffff' }, // 未参与的颜色
        { start: 2, end: 2, color: '#EDECEC' }, // 参与但未点亮的颜色
        { start: 3, end: 3, color: '#E95656' }  // 点亮的颜色
      ]
    }
  };
  chart.setOption(option);
  return chart;
}
function initChartLogin(canvas, width, height) {
  const getPixelRatio = () => {
    let pixelRatio = 0
    wx.getSystemInfo({
      success: function (res) {
        pixelRatio = res.pixelRatio
      },
      fail: function () {
        pixelRatio = 0
      }
    })
    return pixelRatio
  }
  var dpr = getPixelRatio()
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr
  });
  canvas.setChart(chart);
  echarts.registerMap('china', geoJson)
  // 去掉地图点击变色
 chart.on("mouseover", function (params){
  if (params.componentType === 'series') {
    chart.dispatchAction({
      type: 'downplay'
    });
  }
});    

  var option = {
    geo: [
      {
        // 地理坐标系组件
        map: "china",
        roam: false, // 可以缩放和平移
        // symbol: 'http://oss-test.kiscloud.net/image/other/other/20201104/20201104123425_618.png',
        aspectScale: 0.8, // 比例
        layoutCenter: ["50%", "38%"], // position位置
        layoutSize: 370, // 地图大小，保证了不超过 370x370 的区域
        label: {
          // 图形上的文本标签
          normal: {
            show: true,
            textStyle: {
              color: "#333",
              fontSize: '8'
            }
          }
        },
        itemStyle: {
          // 图形上的地图区域
          normal: {
            borderColor: "#ccc",
            borderType: "dashed",
            areaColor: "#fff"
          }
        }
      }
    ],
    series: [
      {
        type: 'map',
        mapType: 'china',
        // zoom: 2,
        geoIndex: 0,
        roam: false, // 鼠标是否可以缩放
        label: {
          normal: {
            show: false
          },
          emphasis: {
            show: false
          }
        },
        data: []
      }
    ],
    dataRange: {
      x: '-1000px',
      y: '-1000px',
      splitList: [
        { start: 1, end: 1, color: '#ffffff' }, // 未参与的颜色
        { start: 2, end: 2, color: '#EDECEC' }, // 参与但未点亮的颜色
        { start: 3, end: 3, color: '#E95656' }  // 点亮的颜色
      ]
    }
  };
  chart.setOption(option);
  return chart;
}

let _this,provinceData = [],userMedalData = []
Page({
  /**
   * 页面的初始数据
   */
  data: {
    navigationHeight: 64,
    navigationTop: 26,
    navigationLeft: 10,
    capsuleWidth: 87,
    lightNum: 0,
    ec:{
      onInit: initChart
    },
    ecLogin: {
      onInit: initChartLogin
    },
    showMap: false,
    ruleShow: false,
    awardShow: false,
    assets: {},
    activityRule: {},
    activityStatus: 1,
    hasMedals: false,
    userInfo: {},
    awardInfo: {},
    title: '',
    isLogin: true
  },
  goRank() {
    wx.navigateTo({
      url: `/activityModule/activity/collectCards/medal/rank/index?activityId=${this.data.activityId}&nickname=${this.data.userInfo.nickname}&avatarUrl=${this.data.userInfo.avatarUrl}&memberId=${this.data.userInfo.memberId}&appletMobile=${this.data.userInfo.appletMobile}`
    })
  },
  goRepeat() {
    if (this.data.hasMedals && this.data.activityStatus === 1) {
      wx.navigateTo({
        url: `/activityModule/activity/collectCards/medal/repeat/index?activityId=${this.data.activityId}`
      })
    }
  },
  goExchange() {
    if (this.data.activityStatus === 1) {
      wx.navigateTo({
        url: `/activityModule/activity/collectCards/medal/exchange/index?activityId=${this.data.activityId}&dust=${this.data.assets.dust}&dustAwards=${JSON.stringify(this.data.activityRule.dustAwards)}`
      })
    }
  },
  closeRule() {
    this.setData({
      ruleShow: false
    })
  },
  lookRules() {
    this.setData({
      ruleShow: true
    })
  },
  closeAward() {
    this.setData({
      awardShow: false
    })
  },
  getAwards() {
    activityModel.getAwardMedalList({
      merchantId: wx.getStorageSync('merchantId'),
      activityId: this.data.activityId,
      memberId: this.data.userInfo.memberId
    }).then(data => {
      data.awards = (data.awards || []).map(item => {
        const split = item.createDate.split(' ')
        return {
          ...item,
          _date: split[0],
          _time: split[1]
        }
      })
      this.setData({
        awardInfo: data || {}
      })
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },
  lookAward() {
    if (this.data.awardInfo.awards && this.data.awardInfo.awards.length) {
      this.getAwards()
      this.setData({
        awardShow: true
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    _this = this
    this.setData({
      activityId: options.id
    })
    const navigationBtnObj = wx.getMenuButtonBoundingClientRect()
    wx.getSystemInfo({
      success: res => {
        this.setData({
          navigationHeight: res.statusBarHeight + navigationBtnObj.height + (navigationBtnObj.top - res.statusBarHeight) * 2,
          navigationTop: navigationBtnObj.top,
          navigationLeft: res.windowWidth - navigationBtnObj.right,
          capsuleWidth: navigationBtnObj.width
        })
      }
    })
  },
  goback() {
    wx.navigateBack({
      fail() {
        wx.redirectTo({
          url: '/pages/index/index',
        })
      }
    })
  },
  getMedalDetail () {
    activityModel.getMedalDetail({
      merchantId: wx.getStorageSync('merchantId'),
      activityId: this.data.activityId
    }).then(data => {
      this.setData({
        activityStatus: data.activityStatus,
        activityRule: JSON.parse(data.activityRule),
        title: data.activityName
      })
      wx.setStorageSync('badgeImageUrl', this.data.activityRule.badgeImage)
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },
  getAsset() {
    activityModel.getMedalAsset({
      activityId: this.data.activityId
    }).then(data => {
      this.setData({
        assets: data || {}
      })
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },
  getLists() {
    activityModel.getRepeatMedal({
      activityId: this.data.activityId
    }).then(data => {
      const medals = (data || []).map(item => {
        item.badges--
        return item
      }).filter(item => !!item.badges)
      this.setData({
        hasMedals: !!medals.length
      })
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },
  getMemberInfo() {
    memberModel.userInfo({
      merchantId: wx.getStorageSync('merchantId')
    }).then(data => {
      this.setData({
        userInfo: data
      })
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },
  getMedalProList() {
    activityModel.getMedalProList({
      merchantId: wx.getStorageSync('merchantId'),
      activityId: this.data.activityId
    }).then(data => {
      provinceData = data.filter(item => item.shopList.length > 0)
      activityModel.getMedalLightProList({
        merchantId: wx.getStorageSync('merchantId'),
        activityId: this.data.activityId
      }).then(data => {
        userMedalData = data
        wx.setStorageSync('medalProvinceData', provinceData)
        wx.setStorageSync('userMedalData', userMedalData)
        this.setData({
          showMap: true
        })
      }).catch(err => {
        wx.showToast({
          title: `${err.error}`,
          icon: 'none',
          duration: 2000
        })
      })
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },
  getUserInfo({ detail }) {
    const { encryptedData, iv } = detail
    if (encryptedData) {
      this.setData({
        encryptedDataUser: encryptedData,
        ivUser: iv,
        phoneShow: true
      })
    }
  },
  refresh() {
    this.setData({
      isLogin: true
    })
    this.getAsset()
    this.getLists()
    this.getAwards()
    this.getMemberInfo()
    this.getMedalProList()
  },
  renderMap() {
    const mapCom = this.selectComponent('#mychart-dom-bar')
    mapCom.init((canvas, width, height, dpr) => {
      const getPixelRatio = () => {
        let pixelRatio = 0
        wx.getSystemInfo({
          success: function (res) {
            pixelRatio = res.pixelRatio
          },
          fail: function () {
            pixelRatio = 0
          }
        })
        return pixelRatio
      }
      var dpr = getPixelRatio()
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr
      });
      canvas.setChart(chart);
      echarts.registerMap('china', geoJson)
      chart.on('click', function (params) {
        if (params.componentType === 'series') {
          if (params.name) {
            wx.navigateTo({
              url: '/activityModule/activity/collectCards/medal/areaRank/index?provinceId=' + provinceData.filter(item => item.provinceName.indexOf(params.name)!=-1)[0].provinceId,
            })
          }
        }
      })
      let allpro = []
      provinceData.forEach(item => {
        if (userMedalData.map(item => item.provinceId).includes(item.provinceId)) {
          if (item.shopList.length === userMedalData.filter(useritem => useritem.provinceId === item.provinceId)[0].shopList.length) {
            allpro.push({
              name: item.provinceName.replace(/省|市/g,''),
              value: 3
            })
          }else{ 
            allpro.push({
              name: item.provinceName.replace(/省|市/g,''),
              value: 2
            })
          }
        }else{
          allpro.push({
            name: item.provinceName.replace(/省|市/g,''),
            value: 1
          })
        }
      })
      var option = {
        geo: [
          {
            // 地理坐标系组件
            map: "china",
            roam: true, // 可以缩放和平移
            // symbol: 'http://oss-test.kiscloud.net/image/other/other/20201104/20201104123425_618.png',
            aspectScale: 0.8, // 比例
            layoutCenter: ["50%", "38%"], // position位置
            layoutSize: 370, // 地图大小，保证了不超过 370x370 的区域
            label: {
              // 图形上的文本标签
              normal: {
                show: true,
                textStyle: {
                  color: "#333",
                  fontSize: '8'
                }
              }
            },
            itemStyle: {
              // 图形上的地图区域
              normal: {
                borderColor: "#424242",
                areaColor: "#fff"
              }
            }
          }
        ],
        series: [
          {
            type: 'map',
            mapType: 'china',
            // zoom: 2,
            geoIndex: 0,
            roam: false, // 鼠标是否可以缩放
            label: {
              normal: {
                show: false
              },
              emphasis: {
                show: false
              }
            },
            data: allpro
          }
        //   {
                    
        //     type: 'scatter',
        //     roam : false,
        //     symbol: 'http://oss-test.kiscloud.net/image/other/other/20201104/20201104123425_618.png',
        //     symbolSize: 30,
        //     coordinateSystem: 'geo',
        //     data: convertData(allpro.filter(item => item.value == 3)),
        //     label: {
        //         emphasis: {
        //             show: false
        //         }
        //     }
        // }
        ],
        dataRange: {
          x: '-1000px',
          y: '-1000px',
          splitList: [
            { start: 1, end: 1, color: '#ffffff' }, // 未参与的颜色
            { start: 2, end: 2, color: '#EDECEC' }, // 参与但未点亮的颜色
            { start: 3, end: 3, color: '#E95656' }  // 点亮的颜色
          ]
        }
      };
      chart.setOption(option);
    })
  },
  deleteMap() {
    this.setData({
      showMap: false
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    app.getInfo().then(({data}) => {
      this.setData({
        isLogin: data.login
      })
      wx.setStorageSync('merchantId', data.merchantId)
      this.getMedalDetail()
      if (data.login) {
        this.getAsset()
        this.getLists()
        this.getAwards()
        this.getMemberInfo()
        this.getMedalProList()
      }
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: this.data.title,
      imageUrl: this.data.activityRule.badgeShareImage,
      path: `activityModule/activity/collectCards/medal/index?id=${this.data.activityId}`
    }
  }
})
